package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import com.sky.vo.UserLoginVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class UserServiceImpl implements UserService {
    @Autowired
    UserMapper userMapper;
    @Autowired
    private WeChatProperties weChatProperties;

    @Override
    public User login(UserLoginDTO userLoginDTO) {
        /**
         * 1. 通过httpclient构造登陆凭证校验请求
         * 2. 解析响应结果，获取openid
         * 3. 判断是否为新用户，根据openid查询user表
         *
         * 4.如果是新用户，初始化用户数据添加到user表
         * 5.如果是老用户，返回user对象
         */
        String path="https://api.weixin.qq.com/sns/jscode2session";
        Map<String,String> map=new HashMap<>();
        map.put("appid",weChatProperties.getAppid());
        map.put("secret",weChatProperties.getSecret());
        map.put("js_code",userLoginDTO.getCode());
        map.put("grant_type","authorization_code");
        String result=HttpClientUtil.doGet(path,map);
        log.info("微信响应结果：{}",result);
        //将result解析成Object格式
        JSONObject jsonObject= JSON.parseObject(result);
        String openid=jsonObject.getString("openid");
        if(openid==null)
            throw new LoginFailedException("登录失败");

        User user=userMapper.selectByOpenid(openid);
        if(user==null){
            //代表新用户，需要初始化！
            User u=new User();
            u.setOpenid(openid);
            u.setCreateTime(LocalDateTime.now());
            u.setName(openid.substring(0,12));
            userMapper.insert(u);
            return u;
        }
        return user;

    }
}
